<template>
    <!-- Main content -->
    <div>
        <div class="row">
            <div class="col-xs-12">
                <theme-box title="营销分钱规则列表">
                    <form class="form-inline" @submit.prevent v-el:form>
                        <form-select title="电子券类型" :sreach="true" :up-table="true" :options="type" name="couponType"></form-select>
                        <form-select title="核销标识" :sreach="true" :up-table="true" name="flag" id="verFlag" :options="flag"></form-select>

                        <button type="reset" @click="reset" class="btn btn-warning pull-right">重置</button>
                        <v-button theme="primary" @click="search" class="pull-right">查询</v-button>
                    </form>
                    <table class="table table-bordered table-striped" style="width:100%" v-el:table>
                    </table>
                </theme-box>
            </div>
            <!-- /.col -->
        </div>
        <modal-container title="编辑" v-el:modal v-ref:modal class="edit-modal" theme="big">
            <form @submit.prevent @reset.prevent v-el:mform>
                <div class="modal-body">
                    <table-modal :item="item" :columns-set="columnsSet" v-ref:item></table-modal>
                </div>

                <div class="modal-footer">
                    <v-button class="pull--left" data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
                    <v-button theme="primary" type="submit">保存</v-button>
                </div>
            </form>

        </modal-container>
        <!-- /.row -->
    </div>
    <!-- /.content -->
</template>

<style lang="less" scoped>
    .form-inline .btn+.btn {
        margin-right: 10px;
    }
    .form-inline .form-group+.form-group {
        margin-left: 20px;
    }
    .form-inline #verFlag{
        margin-left:2%!important;
    }
</style>
<script>
    import {
        dateTime,
        createDataTable
    } from 'ui/collections/general.js'
    var serialize = require('form-serialize');
    import {dateFormat} from "lib/method.js"

    var dataTable;
    var columnsSet;
    export default {
        data: () => ({
            shareLevl:'',
            item: {},
            columnsSet: [],
            type:[
                {key: "全部",value: ""},
                {key: "折扣券",value: "rebate"},
                {key: "抵用券",value: "voucher"},
                {key: "代金券",value: "cash"},
                {key: "礼品券",value: "present"},
                {key: "票务",value: "ticket"},
            ],
            flag:[
                {key: "全部",value: ""},
                {key: "核销后",value: "0"},
                {key: "核销前",value: "1"},
            ]
        }),
        methods: {
            //还原弹出框位置
            resetBindDrag() {
                this.$refs.modal._resetBindDrag();
            },
            //查询按钮
            search: function() {
                dataTable.ajax.reload();
            },
            //重置按钮
            reset: function() {
                $(".form-inline")[0].reset();
                dataTable.ajax.reload();
            }
        },
        created() {
            //datatable所用数组
            columnsSet = [{
                title: "商户号",
                data: "mchtId",
                visible:false,
                edit: true,
                readonly:true,
                className: "operate"
            },{
                title: "商户名称",
                data: "mchtName",
                edit: true,
                readonly:true,
                className: "operate"
            },{
                title: "规则编号",
                data: "ruleId",
                edit: true,
                readonly:true,
                className: "operate"
            },{
                title: "规则名称",
                data: "ruleName",
                edit: true,
                className: "operate"
            },{
                title: "单张营销金额",
                data: "markAmt",
                edit: true,
                className: "operate"
            },{
                title: "电子券类型",
                data: "couponType",
                options: [
                    {key: "折扣券",value: "rebate"},
                    {key: "抵用券",value: "voucher"},
                    {key: "代金券",value: "cash"},
                    {key: "礼品券",value: "present"},
                    {key: "票务",value: "ticket"}
                ],
                className: "operate",
                render: function (data) {
                    var value;
                    if (data == "rebate") {
                        value = '折扣券'
                    } else if (data == "voucher") {
                        value = '抵用券'
                    } else if (data == "cash"){
                        value = "代金券"
                    } else if (data == "present"){
                        value = "礼品券"
                    } else{
                        value = "票务"
                    }
                    return value;
                }
            },
                {
                    title: "核销标识",
                    data: "verFlag",
                    options: [
                        {key: "核销后",value: "0"},
                        {key: "核销前",value: "1"},
                    ],
                    className: "operate",
                    render: function(data) {
                        return (data == 0) ? "核销后" : "核销前"
                    }
                },
                {
                    title: "芸券比例",
                    data: "yqProp",
                    edit: true,
                    readonly:true,
                    className: "operate"
                },
                {
                    title: "代理商比例",
                    data: "agentProp",
                    edit: true,
                    className: "operate"
                },
                {
                    title: "用户比例",
                    data: "usrProp",
                    edit: true,
                    className: "operate"
                },
                {
                    title: "代理商户比例",
                    data: "agentMcht",
                    edit: true,
                    className: "operate"
                },
                {
                    title: "代理店员比例",
                    data: "agentOpr",
                    edit: true,
                    className: "operate"
                },
                {
                    title: "扫码比例",
                    data: "scanProp",
                    edit: true,
                    className: "operate"
                },
                {
                    title: "使用比例",
                    data: "useProp",
                    edit: true,
                    className: "operate"
                },
                {
                    title: "分享比例",
                    data: "shareProp",
                    edit: true,
                    className: "operate"
                },
                {
                    title: "分享层级",
                    data: "shareLvl",
                    edit:true,
                    className: "operate"
                },
                {
                    title: "层级比例",
                    data: "lvlProp",
                    options:[
                        {key: "1",value: "1"},
                        {key: "2",value: "2"},
                        {key: "3",value: "3"},
                        {key: "4",value: "4"},
                        {key: "5",value: "5"}
                    ],
                    className: "operate"
                },
                {
                    title: "相关操作",
                    className: "operate",
                    width: "160px",
                    render: function(value, type, row) {
                     if(row.isUsed == false){
                         return `
                      <button type="button" class="btn btn-primary btn-sm edit">编辑</button>
                      <button type="button" class="btn btn-danger btn-sm delete">删除</button>
                      `
                     }else{
                         return `
                      <button type="button" class="btn btn-defalt btn-sm">使用中</button>
                      `
                     }
                    }
                }]
        },
        ready: async function() {
            var agentPropWatch = function () {
            };
            var usrPropWatch = function () {
            };
            var sharePropWatch = function () {
            };
            var scanPropWatch = function () {
            };
            var agentMchtWatch = function () {
            };
            var agentOprWatch = function () {
            };
            var usePropWatch = function () {
            };
            var shareLvlWatch = function () {
            };
            dateTime({
                format: "yyyy-mm-dd",
                minView: "2"
            })
            this.$set("columnsSet", columnsSet)
            var self = this;
            //创建dataTable
            dataTable = $(this.$els.table).DataTable({
                "columns": this.columnsSet, //定义列
                "ajax": async function(data, callback, settings) {
                    var page = [{
                        "name": "iDisplayStart",
                        "value": 1 + data.start / data.length
                    }, {
                        "name": "iDisplayLength",
                        "value": data.length
                    }];
                    //表单序列化数据
                    var _data = serialize(self.$els.form, {
                        hash: true,
                        disabled: true,
                        empty: true
                    });
                    _data.aoData = JSON.stringify(page);
                    //发送请求
                    var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId;
                    _data.mchtId = mchtId;
                    var result = await self.$post({
                        url: "/api/v2" + projectName_Url + "/plat/rule/query",
                        data:_data,
                        method: "POST"
                    })
                    if (result.respCode != "00") {
                        Midway.alert({
                            title: "操作失败",
                            content: result.content
                        })
                    }
                    //取出返回的层级比例 让页面显示分数
                    for(var i = 0;i<result.content.list.length;i++){
                        if(result.content.list[i].lvlProp != '0'){
                            result.content.list[i].lvlProp = '1/'+ result.content.list[i].lvlProp;
                        }else{
                            result.content.list[i].lvlProp = 0;
                        }
                    }
                    callback({
                        recordsTotal: result.content.total,
                        recordsFiltered: result.content.total,
                        data: result.content.list || []
                    })
                }
            });


            $(self.$el).on("click", ".edit", function() {
                var Row = $(this).closest('tr').get(0);
                const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
                self.item = dataArray;
                dateTime()
                //代理商比例为空 代理商户和店员不填
                agentPropWatch()
                agentPropWatch = self.$refs.item.$watch("item.agentProp", function (v) {
                    if (v == '' || v == '0') {
                        self.columnsSet.find(data => data.data == "agentMcht").edit = false;
                        self.columnsSet.find(data => data.data == "agentOpr").edit = false;
                        $(self.$els.mform.agentProp).rules("remove", "int");
                    } else {
                        self.columnsSet.find(data => data.data == "agentMcht").edit = true;
                        self.columnsSet.find(data => data.data == "agentOpr").edit = true;
                        $(self.$els.mform.agentProp).rules("add", {
                            int:true
                        });
                    }
                });
                //用户比例为空
                usrPropWatch()
                usrPropWatch = self.$refs.item.$watch("item.usrProp", function (v) {
                    if (v == '' || v == '0') {
                        self.columnsSet.find(data => data.data == "scanProp").edit = false;
                        self.columnsSet.find(data => data.data == "useProp").edit = false;
                        self.columnsSet.find(data => data.data == "shareProp").edit = false;
                        self.columnsSet.find(data => data.data == "shareLvl").edit = false;
                        self.columnsSet.find(data => data.data == "lvlProp").options = '';
                        $(self.$els.mform.usrProp).rules("remove", "int");
                    } else {
                        self.columnsSet.find(data => data.data == "scanProp").edit = true;
                        self.columnsSet.find(data => data.data == "useProp").edit = true;
                        self.columnsSet.find(data => data.data == "shareProp").edit = true;
                        self.columnsSet.find(data => data.data == "shareLvl").edit = true;
                        if(this.shareLevl == '' || this.shareLevl == '0'){
                            self.columnsSet.find(data => data.data == "lvlProp").options = '';
                        }else{
                            self.columnsSet.find(data => data.data == "lvlProp").options = [
                                {key: "1",value: "1"},
                                {key: "2",value: "2"},
                                {key: "3",value: "3"},
                                {key: "4",value: "4"},
                                {key: "5",value: "5"}
                            ]
                        }
                        $(self.$els.mform.usrProp).rules("add", {
                            int:true
                        });
                    }
                });
                //有扫码比例
                scanPropWatch()
                scanPropWatch = self.$refs.item.$watch("item.scanProp", function (v) {
                if(v != '' && v != '0'){
                    $(self.$els.mform.scanProp).rules("add", {
                        int:true
                    });
                }else{
                    $(self.$els.mform.scanProp).rules("remove", "int");
                }
                });
//               有分享层级  显示层级比例
                shareLvlWatch()
                shareLvlWatch = self.$refs.item.$watch("item.shareLvl", function (v) {
                    this.shareLevl = v;
                    if (v == '' || v == '0') {
                        self.columnsSet.find(data => data.data == "lvlProp").options = '';
                    } else {
                        self.columnsSet.find(data => data.data == "lvlProp").options = [
                            {key: "1",value: "1"},
                            {key: "2",value: "2"},
                            {key: "3",value: "3"},
                            {key: "4",value: "4"},
                            {key: "5",value: "5"}
                        ];
                    }
                });
                //截取分数的分母 重新赋值修改弹框显示整数
                if(dataArray.lvlProp != '0'){
                    dataArray.lvlProp = dataArray.lvlProp.slice(2);
                }else{

                }
                //编辑框验证、保存、提交
                $(self.$els.mform).validate(self.item.valdate = {
                    async submitHandler() {
                        var form = self.$els.mform;
                        var _data = serialize(form, { hash: true, disabled:true, empty:true });
                        //芸券比例默认传20
//                        _data.yqProp = '20';
                        //传当前登录的操作员id
                        var oprId = JSON.parse(localStorage.getItem("id_token")).oprId
                        _data.updOpr = oprId;
                        //芸券比例 + 代理商比例 + 用户比例 = 100
                        self.item.yqProp = ( self.item.yqProp == ''?0:parseInt(self.item.yqProp));
                        self.item.agentProp  = ( self.item.agentProp == ''?0:parseInt(self.item.agentProp));
                        self.item.usrProp  = ( self.item.usrProp == ''?0:parseInt(self.item.usrProp));
                        if(self.item.yqProp + self.item.agentProp + self.item.usrProp != '100'){
                            Midway.alert({title:"操作提示",content:"芸券比例,代理商比例,用户比例的和为100"});
                            return false;
                        }
                        //代理商比例不为空时 代理商户比例+代理店员比例=100
                        if(_data.agentProp != '' && _data.agentProp != '0'){
                            self.item.agentMcht  = ( self.item.agentMcht == ''?0:parseInt(self.item.agentMcht));
                            self.item.agentOpr  = ( self.item.agentOpr == ''?0:parseInt(self.item.agentOpr));
                            if(self.item.agentMcht + self.item.agentOpr != '100'){
                                Midway.alert({title:"操作提示",content:"代理商户比例与代理店员比例的和为100"});
                                return false;
                            }
                        }
                        //扫码比例 分享比例 使用比例 三个必填一项
                        if(_data.usrProp != '' && _data.usrProp != '0') {
                            if (self.item.scanProp == '' && self.item.shareProp == '' && self.item.useProp == '') {
                                Midway.alert({title: "操作提示", content: "扫码比例、分享比例、使用比例至少填一项"});
                                return false;
                            }
                            //扫码比例+分享比例+使用比例 = 100
                            self.item.scanProp  = ( self.item.scanProp == ''?0:parseInt(self.item.scanProp));
                            self.item.shareProp  = ( self.item.shareProp == ''?0:parseInt(self.item.shareProp));
                            self.item.useProp  = ( self.item.useProp == ''?0:parseInt(self.item.useProp));
                            if(self.item.scanProp + self.item.shareProp + self.item.useProp != '100'){
                                Midway.alert({title:"操作提示",content:"扫码比例、分享比例、使用比例的和为100"});
                                return false;
                            }
                        }
                        //如果分享比例为0 层级比例传0
                        if(_data.shareProp == '0'){
                            _data.lvlProp = '0';
                        }else{
                            _data.lvlProp = _data.lvlProp;
                        }
                        //如果分享比例不为0 层级比例不能为0
                        if(_data.shareProp != '0'&&_data.lvlProp == ''){
                            Midway.alert({title:"操作提示",content:'有分享比例，层级比例不能为空'});
                            return false;
                        }

                        //分享层级 和 层级比例要么都为1，要么都不为1
                        if(_data.shareLvl > 1 && _data.lvlProp == 1){
                            Midway.alert({title:"操作提示",content:"分享层级大于1时，层级比例不能为1"});
                            return false;
                        }else if(_data.shareLvl== 1 && _data.lvlProp != 1){
                            Midway.alert({title:"操作提示",content:"分享层级等于1时，层级比例只能为1"});
                            return false;
                        }

                        var result = await self.$post({
                            url: "/api/v2" + projectName_Url + "/plat/rule/update/"+ _data.ruleId,
                            data: _data,
                            method: "POST"
                        });
                        Midway.alert({title:"操作提示",content:result.errorInfo})

                        dataTable.ajax.reload(null, false);
                        $(self.$els.modal).modal('hide');
                        self.resetBindDrag()
                    },
                    rules: {
                        agentProp:{
                            min:0,
                        },
                        usrProp:{
                            min:0,
                        },
                        agentMcht:{
                            min:0,
                        },
                        agentOpr:{
                            min:0,
                        },
                        scanProp:{
                            min:0,
                        },
                        useProp:{
                            min:0,
                        },
                        shareProp:{
                            min:0,
                        },
                        shareLvl:{
                            min:0,
                        },
                        markAmt:{
                            min:0,
                            int:true,
                            required:true
                        },
                        ruleName:{
                            required:true,
                            maxlength:32
                        }
                    }
                });
                //分享比例不为空 分享层级必填 最小1最大5
                sharePropWatch()
                sharePropWatch = self.$refs.item.$watch("item.shareProp", function (v) {
                  if(v != "" && v != '0'){
                      $(self.$els.mform.shareProp).rules("add", {
                          int:true
                      });
                      self.columnsSet.find(data => data.data == "shareLvl").edit = true;
                      $(self.$els.mform.shareLvl).rules("add", {
                          required:true,
                          max: 5,
                          min:1,
                          int:true
                      });
                      self.columnsSet.find(data => data.data == "lvlProp").options = [
                          {key: "1",value: "1"},
                          {key: "2",value: "2"},
                          {key: "3",value: "3"},
                          {key: "4",value: "4"},
                          {key: "5",value: "5"}
                      ]
                  }else{
                      $(self.$els.mform.shareLvl).rules("remove", "required");
                      $(self.$els.mform.shareProp).rules("remove", "int");
                      self.columnsSet.find(data => data.data == "shareLvl").edit = false;
                      self.columnsSet.find(data => data.data == "lvlProp").options = '';
                  }
                });
                //监听 有值 只能填整数
                agentMchtWatch()
                agentMchtWatch = self.$refs.item.$watch("item.agentMcht", function (v) {
                    if(v != "" && v != '0'){
                        $(self.$els.mform.agentMcht).rules("add", {
                            int:true
                        });
                    }else{
                        $(self.$els.mform.agentMcht).rules("remove", "int");
                    }
                });
                agentOprWatch()
                agentOprWatch = self.$refs.item.$watch("item.agentOpr", function (v) {
                    if(v != "" && v != '0'){
                        $(self.$els.mform.agentOpr).rules("add", {
                            int:true
                        });
                    }else{
                        $(self.$els.mform.agentOpr).rules("remove", "int");
                    }
                });
                usePropWatch()
                usePropWatch = self.$refs.item.$watch("item.useProp", function (v) {
                    if(v != "" && v != '0'){
                        $(self.$els.mform.useProp).rules("add", {
                            int:true
                        });
                    }else{
                        $(self.$els.mform.useProp).rules("remove", "int");
                    }
                });
                $(self.$els.modal).modal('show');
            });

            $(self.$el).on("click", ".delete", async function() {
                var Row = $(this).closest('tr').get(0);
                var ruleName = dataTable.row(Row).data().ruleName;
                var id = dataTable.row(Row).data().ruleId;

                await Midway.confirm({
                    title: "删除营销规则",
                    content: "是否要删除营销规则:" + ruleName + "?"
                })
                var result = await self.$post({
                    url: "/api/v2" + projectName_Url + "/plat/rule/delete/"+id,
                    method: "DELETE"
                });
                Midway.alert({title: "操作提示", content: result.errorInfo})
                dataTable.ajax.reload();
            });
        },
        beforeDestroy() {
            $(this.$el).off("click")
        }
    }
</script>
